<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>YOLO 一键自动按键助手</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Microsoft YaHei', sans-serif;
        }
        .main-container {
            margin-top: 20px;
        }
        .card {
            border-radius: 15px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px 15px 0 0 !important;
        }
        .video-container {
            position: relative;
            background: #000;
            border-radius: 10px;
            overflow: hidden;
        }
        .video-feed {
            width: 100%;
            height: 400px;
            object-fit: cover;
        }
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }
        .status-active {
            background-color: #28a745;
            animation: pulse 2s infinite;
        }
        .status-inactive {
            background-color: #dc3545;
        }
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        .log-container {
            max-height: 200px;
            overflow-y: auto;
        }
        .log-item {
            padding: 8px;
            margin: 4px 0;
            background: #f8f9fa;
            border-left: 4px solid #007bff;
            border-radius: 4px;
        }
        .drop-zone {
            border: 2px dashed #007bff;
            border-radius: 10px;
            padding: 40px;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .drop-zone:hover {
            background-color: #e3f2fd;
            border-color: #0056b3;
        }
        .drop-zone.dragover {
            background-color: #e3f2fd;
            border-color: #0056b3;
        }
        .class-item {
            padding: 10px;
            margin: 5px 0;
            background: #fff;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .class-item:hover {
            background: #f8f9fa;
            transform: translateY(-1px);
        }
        .class-item.selected {
            background: #007bff;
            color: white;
            border-color: #0056b3;
        }
        .btn-control {
            padding: 12px 30px;
            font-size: 16px;
            border-radius: 25px;
            transition: all 0.3s ease;
        }
        .btn-start {
            background: linear-gradient(135deg, #28a745, #20c997);
            border: none;
        }
        .btn-stop {
            background: linear-gradient(135deg, #dc3545, #fd7e14);
            border: none;
        }
    </style>
</head>
<body>
    <div class="container main-container">
        <div class="text-center mb-4">
            <h1 class="display-4">
                <i class="fas fa-robot text-primary"></i>
                YOLO 一键自动按键助手
            </h1>
            <p class="lead text-muted">智能目标检测，自动按键触发</p>
        </div>

        <div class="row">
            <!-- 左侧控制面板 -->
            <div class="col-lg-4">
                <!-- 模型加载 -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-upload"></i>
                            模型加载
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="drop-zone" id="dropZone">
                            <i class="fas fa-cloud-upload-alt fa-3x text-primary mb-3"></i>
                            <h5>拖拽YOLO模型文件到此处</h5>
                            <p class="text-muted">或点击选择文件</p>
                            <input type="file" id="modelFile" accept=".pt" style="display: none;">
                        </div>
                        <div id="modelStatus" class="mt-3"></div>
                    </div>
                </div>

                <!-- 目标选择 -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-bullseye"></i>
                            检测目标选择
                        </h5>
                    </div>
                    <div class="card-body">
                        <div id="classList" class="mb-3">
                            <p class="text-muted">请先加载模型</p>
                        </div>
                    </div>
                </div>

                <!-- 按键设置 -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-keyboard"></i>
                            按键设置
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label for="triggerKey" class="form-label">触发按键</label>
                            <select class="form-select" id="triggerKey">
                                <option value="space">空格键</option>
                                <option value="enter">回车键</option>
                                <option value="tab">Tab键</option>
                                <option value="esc">ESC键</option>
                                <option value="a">A键</option>
                                <option value="b">B键</option>
                                <option value="c">C键</option>
                                <option value="1">数字1</option>
                                <option value="2">数字2</option>
                                <option value="3">数字3</option>
                            </select>
                        </div>
                        <div class="row">
                            <div class="col-6">
                                <label for="areaX" class="form-label">X坐标</label>
                                <input type="number" class="form-control" id="areaX" value="0">
                            </div>
                            <div class="col-6">
                                <label for="areaY" class="form-label">Y坐标</label>
                                <input type="number" class="form-control" id="areaY" value="0">
                            </div>
                        </div>
                        <div class="row mt-2">
                            <div class="col-6">
                                <label for="areaWidth" class="form-label">宽度</label>
                                <input type="number" class="form-control" id="areaWidth" value="1920">
                            </div>
                            <div class="col-6">
                                <label for="areaHeight" class="form-label">高度</label>
                                <input type="number" class="form-control" id="areaHeight" value="1080">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 控制按钮 -->
                <div class="card">
                    <div class="card-body text-center">
                        <button id="startBtn" class="btn btn-success btn-control btn-start me-2">
                            <i class="fas fa-play"></i>
                            开始检测
                        </button>
                        <button id="stopBtn" class="btn btn-danger btn-control btn-stop" disabled>
                            <i class="fas fa-stop"></i>
                            停止检测
                        </button>
                    </div>
                </div>
            </div>

            <!-- 右侧预览面板 -->
            <div class="col-lg-8">
                <!-- 实时预览 -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-video"></i>
                            实时检测预览
                            <span id="statusIndicator" class="status-indicator status-inactive"></span>
                            <span id="statusText">未运行</span>
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="video-container">
                            <img id="videoFeed" class="video-feed" src="" alt="检测画面">
                        </div>
                    </div>
                </div>

                <!-- 检测日志 -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-history"></i>
                            按键触发日志
                        </h5>
                    </div>
                    <div class="card-body">
                        <div id="logContainer" class="log-container">
                            <p class="text-muted">等待检测开始...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    <script>
        let modelLoaded = false;
        let detecting = false;
        let selectedClasses = [];

        // 拖拽上传功能
        const dropZone = document.getElementById('dropZone');
        const modelFile = document.getElementById('modelFile');

        dropZone.addEventListener('click', () => modelFile.click());
        dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropZone.classList.add('dragover');
        });
        dropZone.addEventListener('dragleave', () => {
            dropZone.classList.remove('dragover');
        });
        dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropZone.classList.remove('dragover');
            const files = e.dataTransfer.files;
            if (files.length > 0 && files[0].name.endsWith('.pt')) {
                uploadModel(files[0]);
            }
        });

        modelFile.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                uploadModel(e.target.files[0]);
            }
        });

        // 上传模型
        function uploadModel(file) {
            const formData = new FormData();
            formData.append('model', file);

            fetch('/load_model', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    modelLoaded = true;
                    document.getElementById('modelStatus').innerHTML = 
                        `<div class="alert alert-success">${data.message}</div>`;
                    loadClasses();
                } else {
                    document.getElementById('modelStatus').innerHTML = 
                        `<div class="alert alert-danger">${data.message}</div>`;
                }
            })
            .catch(error => {
                console.error('上传错误:', error);
                document.getElementById('modelStatus').innerHTML = 
                    `<div class="alert alert-danger">上传失败</div>`;
            });
        }

        // 加载类别列表
        function loadClasses() {
            fetch('/get_classes')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const classList = document.getElementById('classList');
                    classList.innerHTML = '';
                    
                    data.classes.forEach((className, index) => {
                        const classItem = document.createElement('div');
                        classItem.className = 'class-item';
                        classItem.textContent = `${index}: ${className}`;
                        classItem.onclick = () => toggleClass(index, classItem);
                        classList.appendChild(classItem);
                    });
                }
            });
        }

        // 切换类别选择
        function toggleClass(classIndex, element) {
            if (selectedClasses.includes(classIndex)) {
                selectedClasses = selectedClasses.filter(c => c !== classIndex);
                element.classList.remove('selected');
            } else {
                selectedClasses.push(classIndex);
                element.classList.add('selected');
            }
        }

        // 开始检测
        document.getElementById('startBtn').addEventListener('click', () => {
            if (!modelLoaded) {
                alert('请先加载模型');
                return;
            }
            if (selectedClasses.length === 0) {
                alert('请选择至少一个检测目标');
                return;
            }

            const area = {
                x: parseInt(document.getElementById('areaX').value),
                y: parseInt(document.getElementById('areaY').value),
                width: parseInt(document.getElementById('areaWidth').value),
                height: parseInt(document.getElementById('areaHeight').value)
            };

            const data = {
                classes: selectedClasses,
                key: document.getElementById('triggerKey').value,
                area: area
            };

            fetch('/start_detection', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    detecting = true;
                    document.getElementById('startBtn').disabled = true;
                    document.getElementById('stopBtn').disabled = false;
                    document.getElementById('statusIndicator').className = 'status-indicator status-active';
                    document.getElementById('statusText').textContent = '检测中';
                    document.getElementById('videoFeed').src = '/video_feed';
                    updateStatus();
                } else {
                    alert(data.message);
                }
            });
        });

        // 停止检测
        document.getElementById('stopBtn').addEventListener('click', () => {
            fetch('/stop_detection', {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                detecting = false;
                document.getElementById('startBtn').disabled = false;
                document.getElementById('stopBtn').disabled = true;
                document.getElementById('statusIndicator').className = 'status-indicator status-inactive';
                document.getElementById('statusText').textContent = '未运行';
                document.getElementById('videoFeed').src = '';
            });
        });

        // 更新状态
        function updateStatus() {
            if (detecting) {
                fetch('/get_status')
                .then(response => response.json())
                .then(data => {
                    // 更新日志
                    const logContainer = document.getElementById('logContainer');
                    if (data.key_press_log.length > 0) {
                        logContainer.innerHTML = '';
                        data.key_press_log.forEach(log => {
                            const logItem = document.createElement('div');
                            logItem.className = 'log-item';
                            logItem.innerHTML = `
                                <strong>${log.timestamp}</strong> - 
                                检测到类别 ${log.class}，触发按键: ${log.key}
                            `;
                            logContainer.appendChild(logItem);
                        });
                    }
                })
                .finally(() => {
                    if (detecting) {
                        setTimeout(updateStatus, 1000);
                    }
                });
            }
        }
    </script>
</body>
</html>
